package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.net.bean.MemberLoginSmsBean;
import com.cljz.makepassenger.model.net.bean.ThirdLoginBean;
import com.cljz.makepassenger.present.activity.LoginP;
import com.cljz.makepassenger.utils.CommonUtils;
import com.cljz.makepassenger.utils.T;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/1.
 */

public class LoginActivity extends BaseActivity<LoginP> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.iv_ok)
    ImageView ivOk;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_wx_login)
    ImageView ivWxLogin;
    @BindView(R.id.iv_qq_login)
    ImageView ivQqLogin;
    @BindView(R.id.activity_login)
    LinearLayout activityLogin;

    private boolean isLogin = false;            //获取验证码为false，登录为true
    private Bundle bundle;
    private TimeCount timeCount;
    private Animation outToLeft;
    private Animation inFromRight;
    private Animation outToRight;
    private Animation inFromLeft;
    //友盟实现第三方登录
    private UMShareAPI umShareAPI;

    //调用的iview方法
    @Override
    public void initData(Bundle savedInstanceState) {
        dismissLoadingDialog();
        umShareAPI = UMShareAPI.get(this);
        bundle = new Bundle();
        timeCount = new TimeCount(60000, 1000);
        outToLeft = AnimationUtils.loadAnimation(App.getInstance(), R.anim.out_to_left);
        inFromRight = AnimationUtils.loadAnimation(App.getInstance(), R.anim.in_from_right);
        outToRight = AnimationUtils.loadAnimation(App.getInstance(), R.anim.out_to_right);
        inFromLeft = AnimationUtils.loadAnimation(App.getInstance(), R.anim.in_from_left);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public LoginP newP() {
        return new LoginP();
    }


    @Override
    protected void initListener() {
        super.initListener();
        //订阅事件分发
        RxView.clicks(ivBack)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(1, java.util.concurrent.TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                isLogin = false;
                timeCount.onFinish();
//                changeState();
            }
        });
        RxView.clicks(ivQqLogin)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(1, java.util.concurrent.TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                showLoadingDialog();
                umShareAPI.getPlatformInfo((Activity) App.getInstance(), SHARE_MEDIA.QQ, umAuthListener);
            }
        });
        RxView.clicks(ivWxLogin)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(1, java.util.concurrent.TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                showLoadingDialog();
                umShareAPI.getPlatformInfo((Activity) App.getInstance(), SHARE_MEDIA.WEIXIN, umAuthListener);
            }
        });
        RxTextView.textChanges(etInput)
                .compose(this.<CharSequence>bindToLifecycle())
                .subscribe(new Action1<CharSequence>() {
                    //CharSequence可读可写序列
                    @Override
                    public void call(CharSequence charSequence) {
                        if (!isLogin) {//登录
                            if (CommonUtils.checkPhone(charSequence.toString())) {
                                btnLogin.setEnabled(true);
                                btnLogin.setText("获取验证码");
                                ivOk.setVisibility(View.VISIBLE);
                            } else {
                                btnLogin.setEnabled(false);
                                btnLogin.setText("登录");
                                ivOk.setVisibility(View.INVISIBLE);
                            }
                        } else {//获取验证码
                            if (charSequence.length() == 6) {
                                ivOk.setVisibility(View.VISIBLE);
                                btnLogin.setEnabled(true);
                            } else {
                                ivOk.setVisibility(View.INVISIBLE);
                                btnLogin.setEnabled(false);
                            }
                        }
                    }
                });
        //控制三秒内的点击速度
        RxView.clicks(btnLogin)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(3, java.util.concurrent.TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                if (CommonUtils.isNetworkAvailable()) {
                    showLoadingDialog();
                    if (isLogin) {
                        //验证码验证成功
                        getP().loginBySms(bundle.getString("phone"), etInput.getText().toString());
                    } else {
                        //获取验证码
                        bundle.putString("phone", etInput.getText().toString());
                        getP().getSms(etInput.getText().toString());
                    }
                } else {
                    T.getInstance().showShort("请开启网络");
                }
            }
        });
    }

    public void getSmsSucceed() {
        dismissLoadingDialog();
        isLogin = true;
        changeState();

    }

    public void getSmsFail(String err) {
        dismissLoadingDialog();
        T.getInstance().showShort(err);
    }


    public void changeState() {
        if (isLogin) {
            activityLogin.startAnimation(outToLeft);
            activityLogin.startAnimation(inFromRight);
            ivBack.setVisibility(View.VISIBLE);
            tvTime.setVisibility(View.VISIBLE);
            etInput.setHint("请输入验证码");
            etInput.setText("");
            etInput.setMaxLines(6);
            etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            btnLogin.setText("登录");
            timeCount.start();
        } else {
            activityLogin.startAnimation(outToRight);
            activityLogin.startAnimation(inFromLeft);
            ivBack.setVisibility(View.INVISIBLE);
            tvTime.setVisibility(View.INVISIBLE);
            etInput.setMaxLines(11);
            etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
            etInput.setHint("请输入手机号验证登录");
            etInput.setText(bundle.getString("phone"));
            btnLogin.setText("获取验证码");
        }
    }

    public void loginSucceed(MemberLoginSmsBean.DataBean data) {
        dismissLoadingDialog();
//        Router.newIntent((Activity) App.getInstance())
//                .to(GroupListActivity.class)
//                .data(new Bundle())
//                .launch();
        Router.newIntent((Activity) App.getInstance())
                .to(MainActivity.class)
                .data(new Bundle())
                .launch();
        Router.pop(this);
        T.getInstance().showShort(data.getUser_nickname() + "登录成功");
    }

    public void loginFail(String s) {
        dismissLoadingDialog();
        T.getInstance().showShort(s);
    }

    public void thirdLoginFail(String s) {
        T.getInstance().showShort(s);
    }

    public void thirdLoginSucceed(ThirdLoginBean thirdLoginBean) {
//        Router.newIntent((Activity) App.getInstance())
//                .to(GroupListActivity.class)
//                .data(new Bundle())
//                .launch();
        Router.newIntent((Activity) App.getInstance())
                .to(MainActivity.class)
                .data(new Bundle())
                .launch();
        Router.pop(this);
    }

    //绑定手机
    public void bindPhone(String user_from, String openid, String unionid) {
        Router.newIntent((Activity) App.getInstance())
                .to(BindPhoneActivity.class)
                .data(new Bundle())
                .putString("user_from", user_from)
                .putString("openid", openid)
                .putString("unionid", unionid)
                .launch();
        Router.pop(this);
    }


    private class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            tvTime.setText("接收大概需要" + l / 1000 + "s");
        }

        @Override
        public void onFinish() {
            isLogin = false;
            changeState();
        }
    }

    //onkeydown 事件会在用户按下一个键盘按键时发生。
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLogin) {
                isLogin = false;
                changeState();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //授权开始的回调

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (platform == SHARE_MEDIA.QQ) {
                T.getInstance().showShort("QQ登录成功");

            } else if (platform == SHARE_MEDIA.WEIXIN) {
                T.getInstance().showShort("微信登录成功");
            }
            getP().loginByThird(platform, data);

        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            if (platform == SHARE_MEDIA.QQ) {
                T.getInstance().showShort("QQ登录失败");

            } else if (platform == SHARE_MEDIA.WEIXIN) {
                T.getInstance().showShort("微信登录失败");
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            T.getInstance().showShort("取消登陆");

        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        dismissLoadingDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        timeCount.cancel();
        timeCount = null;
    }
}
